<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/6
 * Time: 9:27
 */

namespace app\api\controller\user;

use app\api\controller\HomeCommon;
use app\api\model\Product;
use app\lib\exception\FailedException;
use app\Validate\IdArrayMustPositive;
use app\Validate\UserCartAddValidate;
use app\Validate\UserCartChangeValidate;
use think\Request;


class ProductCart extends HomeCommon
{
    /**
     * 用户添加购物车
     * product_id 产品id  规格数组 skuList :{ sku:100, number:100}
     * @param Request $request
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function userAddCart(Request $request){
        (new UserCartAddValidate())->goCheck();
        $post = $request->post();
        $check = (new Product())->check_data($post['product_id']);
        if($check['code']!=1){
            throw new FailedException(['msg'=>$check['msg']]);
        }
        $res = (new \app\api\model\ProductCart())->changeCartNumberNew(1,$post['product_id'],$post['skuList'],$check['uid'],$post['user_id']);
        if($res['code']!=1){
            throw new FailedException(['msg'=>$res['msg']]);
        }
        return writeJson(200,[],'加入成功');
    }
    /**
     * 用户修改购物车里面的某个数量
     * product_id 产品id  sku 规格 number 对应的规格数量
     * @param Request $request
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function userChangeCart(Request $request){
        (new UserCartChangeValidate())->goCheck();
        $post = $request->post();
        $check = (new Product())->check_data($post['product_id']);
        if($check['code']!=1){
            throw new FailedException(['msg'=>$check['msg']]);
        }
        $skuList = [
            ['product_id'=>$post['product_id'],'number'=>$post['number']]
        ];
        $res = (new \app\api\model\ProductCart())->changeNumberNew($post['change_type'],$post['product_id'],$skuList,$check['uid'],$post['user_id']);
        if($res['code']!=1){
            throw new FailedException(['msg'=>$res['msg']]);
        }
        return writeJson(200,[],'修改成功');
    }
    /**
     * 加载用户的购物车信息
     * @param Request $request
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function userCartList(Request $request){
        $post = $request ->post();
        $where = [
            ['a.user_id','eq',$post['user_id']],
            ['a.is_invalid','eq',1],
            ['b.status','eq',2],
            ['b.use_status','eq',1],
            ['c.is_publish','eq',2]
        ];
        $field = "a.id as cart_id,a.update_time,a.number,a.hall_id,b.id as uid,b.type,b.name,c.id as product_id,c.cover_img,c.product_name,c.sku_remark,f.price,c.product_price_one";
        $list = (new \app\api\model\ProductCart())
             ->alias("a")
            ->join("om_shop b","a.uid = b.id","right")
            ->join("om_product c","a.product_id = c.id","right")
            ->join("om_product_price f","a.product_id = f.product_id and a.type = f.type and f.delete_time is null","right")
            ->where($where)
            ->order("a.id desc")
            ->field($field)
            ->select();
        $list = $list->toArray();
        $cartList = (new \app\api\model\ProductCart())->getShopProduct($list);

        //购物车商品对应的排序数组
        $productRule = (new Product())->getProductRule($list);
        $productRule = array_values($productRule);
        return writeJson(200,['cartList'=>$cartList,'productRule'=>$productRule]);
    }

    /**
     * 用户删除购物车
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function userDeleteCart(Request $request){
        (new IdArrayMustPositive())->goCheck();
        $post = $request ->post();
        $where = [];
        $where[] =['user_id','eq',$post['user_id']];
        $where[]  = ['id','in',$post['id']];
        $res = (new \app\api\model\ProductCart())->fieldUpdate("delete_time",time(),"",$where);
        if(!$res){
            throw new FailedException(['msg'=>"操作失败"]);
        }
        return writeJson(200,[],'删除成功');
//        $cartList = (new \app\api\model\ProductCart())->selectListWith("product_price",$where);
//        $cartList = $cartList->toArray();
//        $product = [];//将购物车 按产品分组 并吧价格规则放到里面
//        foreach ($cartList as $key=>$value){
//            if(!isset($product[$value['product_id']])){
//                $product [$value['product_id']]= [
//                  'total_number'=>0,
//                  'type'        =>$value['type'],
//                  'product_price'=>$value['product_price']
//                ];
//            }
//            if(!in_array($value['id'],$post['id'])){  //如果未删除 则将数量+到产品下面
//                $product[$value['product_id']]['total_number']+=$value['number'];
//                foreach ($product[$value['product_id']]['product_price'] as $val){//循环价格规则
//                    if($val['min_number']<=  $product[$value['product_id']]['total_number']){//如果数组总数量大于最小起批数量 将价格换成这个类型
//                        $product[$value['product_id']]['type'] = $val['type'];
//                    }else{
//                        $product[$value['product_id']]['type'] = 1;
//                    }
//                }
//            }
//        }
//        foreach ($cartList as $key=>$value){
//            unset($cartList[$key]['product_price']); //先删除产品价格
//            unset($cartList[$key]['create_time']);
//            unset($cartList[$key]['update_time']);
//            if(!in_array($value['id'],$post['id'])){  //如果未删除 将变动后的价格显示在后台
//               $cartList[$key]['type'] = $product[$value['product_id']]['type'];
//            }else{
//                $cartList[$key]['delete_time'] = time();
//            }
//        }
//        $res = (new \app\api\model\ProductCart())->saveAll($cartList);
//        if(!$res){
//            throw new FailedException(['msg'=>"操作失败"]);
//        }
//        return writeJson(200,[],'删除成功');
    }

    /**
     * 用户结算购物车 前面的判断
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userCheckCart(Request $request){
        (new IdArrayMustPositive())->goCheck();
        $post = $request ->post();
        $cartList = (new \app\api\model\ProductCart())->getCart($post);

        $res = (new \app\api\model\ProductCart())->checkCart($cartList,$post["user_id"]);
        if($res['code']!=1){
            throw new FailedException(['msg'=>$res['msg']]);
        }
        (new \app\api\model\ProductCart())->fieldUpdate('is_select',1,"",[['user_id','eq',$post['user_id']]]);
        $res=(new \app\api\model\ProductCart())->fieldUpdate('is_select',2,"",[['user_id','eq',$post['user_id']],['id','in',$post['id']]]);
        if(!$res){
            throw new FailedException(['msg'=>"购物车修改失败"]);
        }
        return writeJson(200,[],'可以结算');
    }

    /**
     * 立即结算
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userBuyNow(Request $request){
        (new UserCartAddValidate())->goCheck();
        $post = $request->post();
        $check = (new Product())->check_data($post['product_id']);
        if($check['code']!=1){
            throw new FailedException(['msg'=>$check['msg']]);
        }
        foreach ($post['skuList'] as &$value){
            $value['product_id'] =$post['product_id'];
            $value['product_name'] = $check['list']['product_name'];
            $value['type'] = $check['shop']['type'];
        }
        $res = (new \app\api\model\ProductCart())->checkCart($post['skuList'],$post["user_id"]);
        if($res['code']!=1){
            throw new FailedException(['msg'=>$res['msg']]);
        }
        return writeJson(200,[],'可以购买');
    }
}